/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        int n=0;
        ListNode* cur=head;
        while(cur)
        {
            cur=cur->next;
            n++;
        }
        n/=k;
        ListNode* newHead=new ListNode(0);
        ListNode* prev=newHead;
        cur=head;

        for(int i=0;i<n;i++)
        {
            ListNode* tmp=cur;
            for(int j=0;j<k;j++)
            {
                ListNode* next=cur->next;
                cur->next=prev->next;
                prev->next=cur;
                cur=next;
            }
            prev=tmp;
        }
        prev->next=cur;
        cur=newHead->next;
        delete newHead;
        return cur;
    }
};
